package at.guigu.web;

import at.guigu.pojo.User;
import at.guigu.service.BrandService;
import at.guigu.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    //1 创建一个私有的UserService对象
    private UserService userService = new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //2 获取用户名和密码以及获取复选框数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 获取复选框数据
        String remember = request.getParameter("remember");
        //3 调用Service查询用户名和密码是否正确
        User user = userService.login(username, password);
        if (user != null) {//用户登陆成功
            //1 判断用户是否勾选复选框（即是否勾选记住账号）
            if ("1".equals(remember)) {
                //1.1 创建Cookie对象
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                //1.2 设置Cookie存活时间——均设置为7天
                c_username.setMaxAge(60 * 60 * 24 * 7);
                c_password.setMaxAge(60 * 60 * 24 * 7);
                //1.3 将其发送到客户端
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            //2 将登陆成功后的User对象，存储到Session中
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            //3 跳转到查询所有页面
            //注意:由于登录界面和查询所有页面的请求没有资源共享，所以使用重定向
            //动态获取虚拟目录
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/selectAllServlet");
        } else {//用户登录失败
            //将错误信息存储到request域中
            request.setAttribute("login_msg", "用户名或密码错误");
            //跳回到用户登录页面即login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}